package com.emapp.lccode.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.UIData
import com.emapp.lccode.BuildConfig
import com.emapp.lccode.R
import com.emapp.lccode.activity.AdminListActivity
import com.emapp.lccode.activity.FeedBackActivity
import com.emapp.lccode.activity.LoginKtActivity
import com.emapp.lccode.activity.X5WebActivity
import com.emapp.lccode.base.BaseApplication
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.base.BaseFragment1
import com.emapp.lccode.bean.UserKt
import com.emapp.lccode.databinding.FragmentMeBinding
import com.emapp.lccode.mode.Main2ViewModel
import com.emapp.lccode.utils.BaseUtil
import com.emapp.lccode.utils.MmkvUtil
import com.emapp.lccode.utils.getColorExt
import com.emapp.lccode.utils.setOnclickNoRepeat
import com.emapp.lccode.utils.showMessage
import com.emapp.lccode.utils.toStartActivity
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.Toaster

class MeKtFragment : BaseFragment1<Main2ViewModel, FragmentMeBinding>() {
    var user: UserKt? = null
    var showUpdate = false
    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        user = BaseApplication.instance.getUser()
        mViewBind.refreshLayout.setOnRefreshListener {
            if (BaseApplication.instance.getUser() != null) {
                mViewBind.refreshLayout.isRefreshing = false
                //mViewModel.getUserInfor()
            } else {
                mViewBind.refreshLayout.isRefreshing = false
            }
        }
        if (user != null) {
            mViewBind.tvName.text = (user?.name)
            if (user?.isChecker() == true){
                mViewBind.tvType.text = "巡检人员"
            }else if (user?.controll_sta==1){
                mViewBind.tvType.text = "监理单位"
            }else if (user?.controll_sta==2){
                mViewBind.tvType.text = "设计单位"
            }
        }
        val v = BaseUtil.getAppVersionName(requireActivity())
        // mViewBind.tvVersion.text = "版本号：$v"
        mViewBind.tvUpdate2.text =
            "(${BaseConfig.versions[BaseConfig.v].name}) ${BuildConfig.BUILD_TYPE}-$v"
        mViewBind.tvUpdate2.setTextColor(resources.getColor(R.color.word_black))
        mViewBind.ivAvatar.setOnClickListener {
            val currentTime = System.currentTimeMillis()
            // 防止快速连击，确保两次点击之间至少有MIN_CLICK_INTERVAL的间隔
            if (currentTime - lastClickTime >1) {
                clickCount++
                lastClickTime = currentTime
                if (clickCount == CLICK_COUNTDOWN) {
                    // 达到5次点击，执行相应操作
                   // onButtonClick5Times()
                    toStartActivity(AdminListActivity::class.java)
                    clickCount = 0 // 重置点击计数器
                }
            }
        }
    }
    private var clickCount = 0 // 点击计数器
    private val CLICK_COUNTDOWN = 6 // 需要连续点击的次数
    private var lastClickTime: Long = 0 // 记录上一次点击的时间，用于防抖动处理
    private val MIN_CLICK_INTERVAL = 1000L // 两次点击之间的最小间隔时间，单位毫秒，可根据需要调整
    override fun lazyLoadData() {
        XXPermissions.with(this) // 不适配 Android 11 可以这样写
            //.permission(Permission.Group.STORAGE)
            .permission(Permission.MANAGE_EXTERNAL_STORAGE) // .permission(Permission.CAMERA)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    showUpdate = false
                    mViewModel.getVersion2(false)
                }

                override fun onDenied(permissions: List<String>, never: Boolean) {}
            })
    }

    @SuppressLint("SetTextI18n")
    override fun createObserver() {///
        mViewModel.run {
            version.observe(viewLifecycleOwner) { result ->
                if (result == null)
                    return@observe
                if (showUpdate) {
                    AllenVersionChecker
                        .getInstance()
                        .downloadOnly(
                            UIData.create().setDownloadUrl(result.domain).setTitle("检测到新版本")
                                .setContent("是否更新？")
                        ).executeMission(requireActivity())
                } else {
                    mViewBind.tvUpdate2.text =  "(${BaseConfig.versions[BaseConfig.v].name}) -发现新版本"
                    mViewBind.tvUpdate2.setTextColor(getColorExt(R.color.red))
                }
                showUpdate = false
            }
        }
    }

    override fun onBindViewClick() {
        setOnclickNoRepeat(mViewBind.tvUs, mViewBind.lvUpdate, mViewBind.tvLogout, mViewBind.tvFeedback) {
            when (it.id) {
                R.id.tv_us -> {
                    val intent = Intent(requireActivity(), X5WebActivity::class.java)
                    intent.putExtra("name", "关于我们")
                    intent.putExtra("path", resources.getString(R.string.company_url))
                    startActivity(intent)
                }
                R.id.tv_feedback -> {
                    val intent = Intent(requireActivity(), FeedBackActivity::class.java)
                    startActivity(intent)
                }
                R.id.lv_update -> {
                    XXPermissions.with(this) // 不适配 Android 11 可以这样写
                        //.permission(Permission.Group.STORAGE)
                        .permission(Permission.MANAGE_EXTERNAL_STORAGE) // .permission(Permission.CAMERA)
                        .request(object : OnPermissionCallback {
                            override fun onGranted(permissions: List<String>, all: Boolean) {
                                showUpdate = true
                                mViewModel.getVersion2(true)
                            }

                            override fun onDenied(permissions: List<String>, never: Boolean) {}
                        })

                }

                R.id.tv_logout -> {
                    showMessage("确定退出登录吗？", "退出登录", "确定", {
                        toStartActivity(LoginKtActivity::class.java)
                        MmkvUtil.putBoolean("isAutoLogin", false)
                        requireActivity().finish()
                    })

                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        clickCount=0
    }
    override fun onDestroyView() {
        super.onDestroyView()
        AllenVersionChecker.getInstance().cancelAllMission()
    }
}